/**
 * Reads the content of the file from the given location (parent folder path
 * relative to the companyhome).
 */
function main() {
	// get node to move
	var nodeRef = args.node;
	var node = search.findNode(nodeRef);

	// get destination node	
	var targetNode;
	if(args.target != null && args.target != "" && args.target != undefined){
		targetNode = search.findNode(args.target);
	} else {
		targetNode = findTarget(node);
	}

	// array that collects moved nodes
	var movedNodes = new Array();

	// move
	if (node.isContainer) {
		createRMFolder(node, targetNode, movedNodes);
	} else {
		node.move(targetNode);
		movedNodes.push(node.nodeRef);
		handleAttachments(node, targetNode, movedNodes);
	}
	
	if (node.isContainer) {
		// delete folder from dl
		node.remove();
	}

	model.movednodes = jsonUtils.toJSONString(movedNodes);
}

/**
 * Creates a rm folder which has the same properties with the node.
 * 
 * @param node
 *            node to copy
 * @param targetNode
 *            copy target
 */
function createRMFolder(node, targetNode, movedNodes){
    // create node
    var repoFormData = new Packages.org.alfresco.repo.forms.FormData();
    repoFormData.addFieldData("prop_rma_ts13298RefCodePart",
                    node.properties["tr:dlRefCodePart"]);
    repoFormData.addFieldData("prop_cm_description", node.properties["cm:description"]);
    repoFormData.addFieldData("prop_cm_name", node.properties["cm:name"]);
    repoFormData.addFieldData("prop_cm_title", node.properties["cm:title"]);
    // repoFormData.addFieldData("alf_destination",
	// "workspace://SpacesStore/dea518df-99aa-4cbd-8121-542290328994");
    var targetFolderNodeRef=targetNode.nodeRef;
    var targetFolderNodeRefStr=targetFolderNodeRef.storeRef.protocol+"://"+targetFolderNodeRef.storeRef.identifier+"/"+targetFolderNodeRef.id;
    repoFormData.addFieldData("alf_destination", targetFolderNodeRefStr);

    var createdNodeRef = formService.saveForm("type", getFolderType(targetNode), repoFormData).toString();
	var createdNode = search.findNode(createdNodeRef);
    
	handleChildren(node, createdNode, movedNodes);
}

function getFolderType(parentNode){
	var parentType = parentNode.typeShort;
	if (parentType == "dod:recordCategory"
			|| parentType == "tsrm:recordSubcategory") {
		return "rma_recordFolder";
	} else if (parentType == "rma:recordFolder"
			|| parentType == "tsrm:recordSubfolder") {
		return "tsrm_recordSubfolder";
	}
}

/**
 * If handling attachments are enabled, moves attachments to the new location of
 * the node.
 * 
 * @param node
 *            node to handle its attachments.
 * @param targetNode
 *            folder to move attachments
 * @param movedNodes
 *            list that holds moved nodes
 */
function handleAttachments(node, targetNode, movedNodes) {
	// handle attachments if required
	if (args.attachment) {
		if (node.isDocument) {
			var attachments = node.childAssocs["{http://www.uekae.tubitak.gov.tr/model/epdk/1.0}ekBelge"];
			if (attachments) {
				for ( var i = 0; i < attachments.length; i++) {
					// also move attachments
					attachments[i].move(targetNode);
					movedNodes.push(attachments[i].nodeRef);
				}
			}
		}
	}
}

/**
 * Recursively handles the childrens' attachments of the folder.
 * 
 * @param node
 *            node to handle its children
 * @param rmEquivalent
 *            rm copy of the node
 * @param movedNodes
 *            list that holds moved nodes
 */
function handleChildren(node, rmEquivalent, movedNodes) {
	var childNodes = node.children;
	for ( var i = 0; i < childNodes.length; i++) {
		var children = childNodes[i];
		if (children.isContainer) {
			createRMFolder(children, rmEquivalent, movedNodes)
		} else {
			children.move(rmEquivalent);
			movedNodes.push(children.nodeRef);
			handleAttachments(children, node, movedNodes);
		}
	}
}

/**
 * Handles the target node of the specified node.
 * 
 * @param node
 *            source node to handle its target node
 */
function findTarget(node) {
	var wholeRefCode = "";
	var refCodePart = "";
	while(node.name != "documentLibrary"){
		refCodePart = node.properties["{http://www.uekae.tubitak.gov.tr/model/content/1.0}dlRefCodePart"];
		if(refCodePart != null && refCodePart != "" && refCodePart != undefined){
			wholeRefCode = wholeRefCode + refCodePart + "/";
		}
		node = node.parent;
	}

	if(wholeRefCode.lastIndexOf("/") > -1){
		wholeRefCode = wholeRefCode.substring(0, wholeRefCode.lastIndexOf("/"));
	}
	
	var rootNode = companyhome.childByNamePath("Sites").childByNamePath("rm").childByNamePath("documentLibrary");
	
	var array = wholeRefCode.split("/");
	var k = array.length;
	
	var codePart = "";
	var targetNode;
	while (k>=1) {
		codePart = array[k-1];
		targetNode = findNodeByRefCodePart(rootNode, codePart);
		
		if(k!=1){ // as long as last element of array
			rootNode = targetNode;
		}
		
		k = k-1;
	}
	
	return targetNode;
}

/**
 * Handles the node by the specified refCodePart
 * 
 * @param node
 *            root node to handle its child according to refCodePart 
 */
function findNodeByRefCodePart(node, refCodePart) {
	if(node!=null){
		var childNodes = node.children;
		for ( var i = 0; i < childNodes.length; i++) {
			if (refCodePart != null && refCodePart != "" && refCodePart != undefined && 
					childNodes[i].properties["{http://www.alfresco.org/model/recordsmanagement/1.0}ts13298RefCodePart"] == refCodePart) {
				return childNodes[i];
			}
		}
	}
	return null;
}

main();